from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from user.models import User, UserPhoto
from user.forms import UserForm, UserPhotoForm
import os
from utils.upload_to_cloud import upload_to_qiniu
import json
from utils.encrypt_id import *

current_dir = os.path.dirname(os.path.dirname(__file__))


@csrf_exempt
def user_view(request):
    if request.method == 'POST':
        print('[POST] received an post request..')
        user_form = UserForm(request.POST, request.FILES)
        if user_form.is_valid():
            new_user = user_form.save(commit=False)
            # check user_email is exist or not
            print('checking is user exist...')
            try:
                user = User.objects.get(user_email=new_user.user_email)
                print(user)
                user_id = encrypt_id(user.id)
                response = {
                    'status': 'info',
                    'message': 'user already exist',
                    'data': {
                        'user_id': user_id
                    }
                }
                return HttpResponse(json.dumps(response))
            except User.DoesNotExist as e:
                print(e)
                new_user.save()
                new_user_id = encrypt_id(new_user.id)
                new_user = User.objects.get(id=new_user_id)
                user_avatar_local_file = current_dir + new_user.user_avatar.url
                if upload_to_qiniu(user_avatar_local_file):
                    # if success upload to qi niu, return url
                    new_user_avatar_url = upload_to_qiniu(user_avatar_local_file)
                    upload_status = 'success'
                    new_user.user_avatar_url = new_user_avatar_url
                    new_user.save()
                    response = {
                        'status': upload_status,
                        'message': 'success upload picture to qi niu.',
                        'data': {
                            'user_id': new_user_id
                        }
                    }
                else:
                    upload_status = 'error'
                    response = {
                        'status': upload_status,
                        'message': 'failed to upload avatar to qi niu.'
                    }
                return HttpResponse(json.dumps(response))
        else:
            response = {
                'status': 'error',
                'message': 'invalid post format'
            }
            return HttpResponse(json.dumps(response))
    else:
        # if method is GET, going get user object using params user_id
        user_id = request.GET.get('user_id', '')
        try:
            user_id = int(user_id)
            try:
                print(user_id)
                user_id = decrypt_id(user_id)
                print(user_id)
                user = User.objects.get(id=user_id)
                print(user)
                user_name = user.user_name
                user_gender = user.user_gender
                user_sign = user.user_sign
                user_email = user.user_email
                user_birth = str(user.user_birthday.year) + '-' + str(user.user_birthday.month) + '-' + str(
                    user.user_birthday.day)
                user_avatar_url = user.user_avatar.url
                response = {
                    'status': 'success',
                    'message': 'find user success',
                    'data': {'user_name': user_name, 'user_sign': user_sign,
                             'user_gender': user_gender, 'user_email': user_email,
                             'user_birth': user_birth,
                             'user_avatar_url': user_avatar_url}
                }
                print(response)
                return HttpResponse(json.dumps(response))
            except User.DoesNotExist:
                response = {
                    'status': 'error',
                    'message': 'user not exist'
                }
                return HttpResponse(json.dumps(response))
        except Exception as e:
            print(e)
            response = {
                'status': 'error',
                'message': 'bad id request'
            }
            return HttpResponse(json.dumps(response))


@csrf_exempt
def login_view(request):
    """
    this method using for login purpose,
    :param request:
    :return:
    """
    if request.method == 'POST':
        # got request json parse user_email and user_password
        try:
            json_data = json.loads(request.body)
            try:
                user_email = json_data['user_email']
                user_password = json_data['user_password']
                try:
                    user = User.objects.get(user_email=user_email)
                    if user.user_password == user_password:
                        user_id = encrypt_id(user.id)

                        response = {
                            'status': 'success',
                            'message': 'login success',
                            'data': {'user_id': user_id}
                        }
                        return HttpResponse(json.dumps(response))
                    else:
                        response = {
                            'status': 'fail',
                            'message': 'login failed, invalid password'
                        }
                        return HttpResponse(json.dumps(response))
                except User.DoesNotExist:
                    response = {
                        'status': 'info',
                        'message': 'user doest not exist.'
                    }
                    return HttpResponse(json.dumps(response))
            except KeyError:
                response = {
                    'status': 'error',
                    'message': 'json key error, send user_email and user_password'
                }
                return HttpResponse(json.dumps(response))
        except Exception as e:
            print(e)
            response = {
                'status': 'error',
                'message': 'json format error'
            }
            return HttpResponse(json.dumps(response))
